/**
 * 业务模块
 */
const mock = require('./mock.json')
const path = require('path')
const fs = require('fs')
const db = require('./mysql/db.js')
// 定义写入函数
function writeF(res) {
  fs.writeFile(path.join(__dirname, 'mock.json'), JSON.stringify(mock, null, 2), 'utf8', (err) => {
    if (err) {
      res.send('写入错误');
      return
    }
    res.redirect('/');
  })
}
// 自动添加数据id
// function maxcode() {
//   let arr = [];
//   mock.forEach((item) => {
//     arr.push(item.id)
//   })
//   return Math.max.apply(null, arr);
// }

// 显示主页面
exports.showIndex = (req, res) => {
  // res.render('index.html', {
  // 	list: mock
  // })
  // 使用数据库的data
  let sql = "select * from book";
  let data = null;
  db.base("book", sql, data, (result) => {
    res.render('index.html', { list: result })
  })
}
// 添加图书页面
exports.toAddBook = (req, res) => {
  res.render('toAddBook.html', {})
}
// 添加图书（post数据）
exports.addBook = (req, res) => {
  let data = req.body;
  // data.id = (maxcode() + 1).toString();
  // mock.push(data)
  // writeF(res)
  let sql = "insert into book set ?"
  db.base("book", sql, data, (result) => {
    res.redirect('/')
  })
}
// 转到修改图书页面
exports.toEditBook = (req, res) => {
  let id = [req.query.id];
  let sql = "select * from book where id = ?"
  db.base("book", sql, id, (result) => {
    res.render('toEditBook.html', result[0])
  })
}

// 提交修改图书数据
exports.editBook = (req, res) => {
  let data = req.body;
  let dataSql = [data.name, data.author, data.lei, data.description, data.id]
  let sql = "update book set name=?,author=?,lei=?,description=? where id =?"
  db.base("book", sql, dataSql, (result) => {
    res.redirect('/')
  })
}

// 删除图书
exports.deleteBook = (req, res) => {
  let id = [req.query.id];
  let sql = "delete from book where id = ?"
  db.base("book", sql, id, (result) => {
    res.redirect('/')
  })
}
